package thread;

import java.util.Map;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-07-28
 * Time: 16:48
 */
class MyTimerTask implements Comparable<MyTimerTask> {
    private long time;
    private Runnable runnable;

    /**
     * @param runnable 具体执行的任务
     * @param delay 是一个相对时间差
     */
    public MyTimerTask (Runnable runnable, long delay) {
        time = System.currentTimeMillis() + delay;
        this.runnable = runnable;
    }
    public long getTime() {
        return time;
    }
    public Runnable getRunnable() {
        return runnable;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
}
class MyTimer {
    private Object object = new Object();
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    /**
     * 定时器的核心方法, 就是把要执行的任务添加到队列中
     * @param runnable 要执行的任务
     * @param delay 相对时间差
     */
    public void schedule(Runnable runnable, long delay) {
        synchronized (object) {
            MyTimerTask task = new MyTimerTask(runnable, delay);
            queue.offer(task);
            object.notify();

        }
    }

    /**
     * 扫面线程:
     *      一方面 负责监控队首元素是否到达执行时间
     *      另一方面 当任务到达执行时间后, 调用run()执行任务.
     */
    public MyTimer() {
        Thread t = new Thread(() -> {
            while (true) {
                try {
                    synchronized (object) {
                        while (queue.isEmpty()) {
                            object.wait();
                        }
                        MyTimerTask myTimerTask = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if(curTime >= myTimerTask.getTime()) {
                            queue.poll();
                            myTimerTask.getRunnable().run();

                            //////
                        } else {
                            object.wait(myTimerTask.getTime() - curTime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
public class Demo22 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1");
            }
        }, 1000);
    }
}
